package com.chennan.algorithm.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author chennan
 * @createTime 2021年11月16日 18:03:00
 */
public class FooBarTest{
    public static void main(String[] args) throws InterruptedException {
        FooBar fooBar = new FooBar(5);
//        ExecutorService executorService = Executors.newFixedThreadPool(5);
//        Thread bar= new Thread(()->{
//            fooBar.foo();
//        });
//        fooBar.bar(bar);
//        fooBar.foo(()-> {
//
//        });
    }
}
class FooBar {

    private int n;

    private Lock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();
    public FooBar(int n) {
        this.n = n;
    }

    public void foo(Runnable printFoo) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                condition.await();
               // printFoo.run() outputs "foo". Do not change or remove this line.
               printFoo.run();
            } finally {
                lock.unlock();
            }
        }
    }

    public void bar(Runnable printBar) throws InterruptedException {

        for (int i = 0; i < n; i++) {
            lock.lock();
            try {
                condition.await();
            // printBar.run() outputs "bar". Do not change or remove this line.
                printBar.run();
            } finally {
                lock.unlock();
            }
        }
    }
}
